<?php

namespace App\Admin\Actions\ProductBatch;

use App\Models\ProductsBatchLossModel;
use App\Models\ProductsBatchModel;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Grid\Displayers\Modal;
use Illuminate\Support\Facades\DB;

class Loss extends RowAction
{
    public $name = '报损';

    public function handle(ProductsBatchModel $model)
    {
        $data = request()->post();

        DB::beginTransaction();

        /** @var ProductsBatchModel $batch */
        $batch = ProductsBatchModel::where('batch_id', $this->getKey())
            ->lockForUpdate()
            ->first();

        if ($batch['stock'] < $data['loss_num']) {
            DB::rollBack();
            return $this->response()->error('库存不足');
        }

        $batch['loss_number'] += $data['loss_num'];

        $batch->save();

        $loss = new ProductsBatchLossModel([
            'batch_id' => $this->getKey(),
            'loss_type' => $data['loss_type'],
            'remark' => $data['remark'],
            'loss_num' => $data['loss_num'],
        ]);

        $loss->save();

        DB::commit();

        return $loss ? $this->response()->success('报损成功')->refresh() : $this->response()->error('报损失败');
    }

    public function form(ProductsBatchModel $model)
    {
        $this->text('product.product_name', '产品名称')->value($model['product']['product_name'])->readonly();
        $this->text('loss_num', '报损数量')->required();
        $this->text('unit', '单位')->value(ProductsBatchModel::MAP_UNIT[$model['unit']])->disable();
        $this->radio('loss_type', '报损类型')->options([1 => '加工损耗', 2 => '质变损耗', 3 => '其他'])
            ->default(1)->required();
        $this->textarea('remark', '报损原因')->placeholder('请输入1～100个字符');
    }

}
